#include "gd32f30x.h"
#include "stdint.h"
#include "stdio.h"
#include "stdlib.h"
#include "cpuusage.h"

#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "semphr.h"

#include "DevicesDelay.h"
#include "DevicesADC.h"
#include "DevicesBeep.h"
#include "DevicesKey.h"
#include "DevicesLed.h"
#include "DevicesMemHeap.h"
#include "DevicesMemPool.h"
#include "DevicesPower.h"
#include "DevicesPWM.h"
#include "DevicesQueue.h"
#include "DevicesRS485.h"
#include "DevicesSPI.h"
#include "DevicesSPIFlash.h"
#include "DevicesTimer.h"
#include "DevicesUart.h"
#include "DevicesWatchDog.h"
#include "DevicesSoftTimer.h"
#include "DevicesList.h"
#include "DevicesTime.h"
#include "DevicesRTC.h"
#include "DevicesCAN.h"
#include "DevicesWatchDog.h"
#include "DevicesUID.h"

#include "DriverLcd.h"

#include "taskSoftTimer.h"
#include "taskNes.h"
#include "taskKey.h"
#include "taskMessageSlave.h"
#include "taskLittleFS.h"
#include "taskSystem.h"


TaskHandle_t g_TaskSystemInitHand = NULL;  /* 系统初始化任务句柄 */

/* SPI Flash 读、写互斥信号量 */
SemaphoreHandle_t g_xSpiFlashSemaphore;


QueueHandle_t g_xBinarySemaphore;



void vApplicationIdleHook( void )
{
    /* CPU占用率计算 */
    vCPUUsageIdleHook();

    /* 喂狗 */
    vWatchdogReload();
}


void vUserSystemInit(void)
{
    vDelayInit();

    ucMcuHardIDRead();

    vRtcInit();

    enumQueueInit();

    vLedInit();

    vKeyInit();

    vSPIFlashInit();

//    cSoftTimerInit();

//    vWatchdogInit();
}

void vTaskSystemInit(void *pvParameters)
{
    printf("FreeRTOS start succeed...\r\n");

    /* 创建递归互斥信号量 */
    g_xSpiFlashSemaphore = xSemaphoreCreateRecursiveMutex();
    
    /* 创建一个二进制信号量 */
    g_xBinarySemaphore = xSemaphoreCreateBinary();
    xSemaphoreGive(g_xBinarySemaphore);


//    xTaskCreate(vTaskKey,               "Key",              256,    NULL, configMAX_PRIORITIES - 2, &g_TaskKeyHand);

//    xTaskCreate(vTaskMessageSlave,      "Message Slave",    512,    NULL, configMAX_PRIORITIES - 3, &g_TaskMessageSlaveHand);

    xTaskCreate(vTaskNes,               "Nes",              1024,    NULL, configMAX_PRIORITIES - 6, &g_TaskNesHand);

//    xTaskCreate(vTaskLittleFS,              "LittleFS",         1024,    NULL, configMAX_PRIORITIES - 8, &g_TaskLittleFSHand);


    vUserSystemInit();

    printf("SystemInit succeed.\r\n");


    while(1)
    {
        vLedRevesal(0xFF);
//        lcd_clear(rand());

        vTaskDelay(500 / portTICK_RATE_MS);
    }


    /* 删除自己 */
    vTaskDelete( NULL );
}
